package vip.ifmm.lehouse.user.service.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import vip.ifmm.lehouse.common.enums.type.EmailMimeType;
import vip.ifmm.lehouse.common.message.EmailSenderMessage;
import vip.ifmm.lehouse.mq.service.api.RocketMqService;
import vip.ifmm.lehouse.user.service.event.SendRegisterCodeEvent;
import vip.ifmm.lehouse.user.service.utils.FileUtil;

/**
 * 发送邮箱注册验证码的事件监听器
 *
 * @author Fish
 * <p>Email: fishinlove@163.com</p>
 * <p>created by 2019/06/17 00:29:46</p>
 */
@Component
@Slf4j
public class SendEmailRegisterCodeEventListener implements ApplicationListener<SendRegisterCodeEvent> {

    // 邮件主题
    private static final String EMAIL_TOPIC = "lehouse 注册验证码";

    // 邮件模板文件
    private static final String EMAIL_TEMPLATE = "email/send_register_code_email_template.html";

    // 消息队列服务
    @Reference(timeout = 5000)
    private RocketMqService mqService = null;

    @Value("${email-queue-topic}")
    private String emailQueueTopic = null;

    @Value("${register-code-expire}")
    private int registerCodeExpiredTime = 90;

    @Override
    public void onApplicationEvent(SendRegisterCodeEvent event) {

        // 根据邮件模板和验证码合成邮件，并交给邮件服务进行发送
        String email = email(event.getCode());
        log.info("发送邮件给 " + event.getToWho() + "，内容是\n" + email);
        sendRegisterCodeMessage(event.getToWho(), email);
    }

    // 发送注册验证码消息
    private void sendRegisterCodeMessage(String toWho, String content) {

        // 创建发送邮件消息
        EmailSenderMessage message = new EmailSenderMessage().setEmailReceivers(new String[]{
                toWho
        }).setEmailTopic(EMAIL_TOPIC).setEmailContent(content).setEmailType(EmailMimeType.HTML);
        message.setMessageExpiredTime(registerCodeExpiredTime);

        mqService.send(emailQueueTopic, "register-code", JSON.toJSONString(message));
    }

    // 得到邮件信息
    private String email(String code) {
        String email = FileUtil.textOf(EMAIL_TEMPLATE);
        if (email == null) {
            email = "验证码：{{registerCode}}";
        }

        return email.replaceAll("\\{\\{registerCode}}", code);
    }
}
